﻿using CefSharp;
using CefSharp.Internals;
using CefSharp.WinForms;
using SharpBrowser.Config;
using SharpBrowser.Handlers;
using SharpBrowser.Utils;
using System;
using System.IO;
using System.Windows;

namespace SharpBrowser.Managers
{
    internal static class BrowserManager
    {

        public static HostHandler _HostHandler;

        private static DownloadHandler dHandler;
        private static ContextMenuHandler mHandler;
        private static LifeSpanHandler lHandler;
        private static KeyboardHandler kHandler;
        private static RequestHandler rHandler;
        private static PermissionHandler pHandler;

        public static void Init(MainForm form)
        {
            if (Cef.IsInitialized != true)
            {
                CefSettings settings = new CefSettings() {
                    //CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache"),
                    // 设置日志级别
                    LogSeverity = LogSeverity.Verbose,
                    //LogFile = Path.Combine(ConfigManager.AppDataPath, "CefSharp", "CefSharp.log")
                };

                var logDir = Path.Combine(ConfigManager.AppDataPath, "CefSharp");
                //MessageBox.Show(logDir);
                logDir.EnsureFolderExists();
                settings.LogFile = Path.Combine(logDir, "CefSharp.log");

                // 尽量避免显卡/驱动相关崩溃：禁用硬件加速
                //settings.CefCommandLineArgs.Add("disable-gpu", "1");
                //settings.CefCommandLineArgs.Add("disable-gpu-compositing", "1");
                //// 避免 WebGL 触发的 GPU stall / 崩溃
                //settings.CefCommandLineArgs.Add("disable-webgl", "1");

                // 禁用沙箱模式（单 exe 应用更稳定）
                settings.CefCommandLineArgs.Add("no-sandbox", "1");
                settings.CefCommandLineArgs.Add("enable-unsafe-swiftshader", "1");

                settings.RemoteDebuggingPort = 9222;

                // 音频相关配置：尝试多种方式避免 MojoAudioOutputIPC 崩溃，同时保留声音功能
                // 1. 禁用 AudioServiceOutOfProcess，让音频在浏览器进程内运行，减少 IPC 问题
                //settings.CefCommandLineArgs.Add(
                //    "disable-features",
                //    "PartitionAllocDanglingPtr,PartitionAllocUnretainedDanglingPtr,AudioServiceOutOfProcess,AudioServiceAudioStreams,MediaFoundationAudio"
                //);

                // 2. 允许自动播放音频（改变初始化时机，可能避免某些初始化失败）
                //settings.CefCommandLineArgs.Add("autoplay-policy", "no-user-gesture-required");

                //// 3. 禁用音频输入调试（减少音频模块的额外开销）
                //settings.CefCommandLineArgs.Add("disable-audio-input-debug-recording", "1");

                //// 4. 强制使用旧的音频后端（WASAPI/DirectSound），避免新的 MediaFoundation 后端导致的 Mojo IPC 问题
                //// 已在 disable-features 中添加 MediaFoundationAudio

                //// 5. 禁用后台网络服务（可能影响音频服务初始化）
                //settings.CefCommandLineArgs.Add("disable-background-networking", "1");

                //// 6. 尝试设置音频缓冲区大小（可能有助于稳定性）
                //settings.CefCommandLineArgs.Add("audio-buffer-size", "4096");

                //// 7. 禁用硬件加速的音频处理（使用软件混音）
                //settings.CefCommandLineArgs.Add("disable-audio-hardware", "1");


                settings.CefCommandLineArgs.Add("disable-extensions", "1");

                // 启用 MP4/H.264 视频播放支持
                // CEF 默认不支持专有编解码器，需要显式启用
                // 注意：如果 CEF 构建版本不包含专有编解码器支持，这些参数可能无效
                
                // 启用 Media Foundation（Windows 上的媒体播放框架，用于 MP4/H.264 播放）
                settings.CefCommandLineArgs.Add("enable-media-foundation", "1");
                
                // 启用 Media Foundation 播放功能
                settings.CefCommandLineArgs.Add("enable-features", "PlatformHEVCDecoderSupport,MediaFoundationPlayback,MediaFoundationH264Encoding");
                
                // 启用硬件视频解码（如果可用）
                settings.CefCommandLineArgs.Add("enable-accelerated-video-decode", "1");
                // 启用硬件视频编码（如果需要）
                settings.CefCommandLineArgs.Add("enable-accelerated-video-encode", "1");
                
                // 允许播放受保护的内容（某些 MP4 可能需要）
                settings.CefCommandLineArgs.Add("enable-protected-media-identifier", "1");
                
                // 允许自动播放音频（MP4 视频通常包含音频轨道）
                settings.CefCommandLineArgs.Add("autoplay-policy", "no-user-gesture-required");
                
                // 确保不禁用媒体相关功能
                // 移除可能禁用媒体播放的参数（如果存在）

                settings.RegisterScheme(new CefCustomScheme
                {
                    SchemeName = BrowserConfig.InternalScheme,
                    SchemeHandlerFactory = new SchemeHandlerFactory()
                });

                //------------------------------------------------------------
                // FIX: this prevents a crash if 2 CefSharp apps are opened at once

                // init cache dirs in AppData Roaming
                var rcPath = Path.Combine(ConfigManager.AppDataPath, "CefCache");
                // fix: CachePath MUST be a child of the RootCachePath as of CEF 128+
                var cPath = Path.Combine(rcPath, "_TempCache");

                // create cache dirs
                rcPath.EnsureFolderExists();
                cPath.EnsureFolderExists();

                settings.RootCachePath = rcPath;
                settings.CachePath = cPath;
                //------------------------------------------------------------

                BrowserConfig.GetCefSettings(settings);

                // 尝试初始化 CEF，如果失败则记录错误
                try
                {
                    Cef.Initialize(settings);
                }
                catch (Exception ex)
                {
                    // 记录初始化失败的错误
                    try
                    {
                        string errorLogPath = Path.Combine(
                            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                            "SharpBrowser", "cef_init_error.txt");
                        Directory.CreateDirectory(Path.GetDirectoryName(errorLogPath));
                        File.AppendAllText(errorLogPath, 
                            $"[{DateTime.Now}] CEF初始化失败: {ex.Message}\n堆栈: {ex.StackTrace}\n\n");
                    }
                    catch { }
                    
                    // 重新抛出异常，让调用者知道初始化失败
                    throw;
                }

            }

            if (dHandler == null)
            {

                dHandler = new DownloadHandler(form);
                lHandler = new LifeSpanHandler(form);
                mHandler = new ContextMenuHandler(form);
                kHandler = new KeyboardHandler(form);
                rHandler = new RequestHandler(form);
                pHandler = new PermissionHandler();
                _HostHandler = new HostHandler(form);

            }
        }

        /// <summary>
        /// Register our handlers with the given CefSharp browser instance.
        /// </summary>
        public static void SetupHandlers(ChromiumWebBrowser browser)
        {
            browser.DownloadHandler = dHandler;
            browser.MenuHandler = mHandler;
            browser.LifeSpanHandler = lHandler;
            browser.KeyboardHandler = kHandler;
            browser.RequestHandler = rHandler;
            browser.PermissionHandler = pHandler;
        }
    }
}